package cn.edu.cdp.dumpling.service.impl;

import cn.edu.cdp.dumpling.dto.DishDto;
import cn.edu.cdp.dumpling.entity.Business;
import cn.edu.cdp.dumpling.entity.Category;
import cn.edu.cdp.dumpling.entity.Dish;
import cn.edu.cdp.dumpling.mapper.DishMapper;
import cn.edu.cdp.dumpling.service.BusinessService;
import cn.edu.cdp.dumpling.service.CategoryService;
import cn.edu.cdp.dumpling.service.DishService;
import cn.edu.cdp.dumpling.util.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    private final CategoryService categoryService;
    private final BusinessService businessService;

    public DishServiceImpl(CategoryService categoryService, BusinessService businessService) {
        this.categoryService = categoryService;
        this.businessService = businessService;
    }
    @Override
    public List<DishDto> list(String category, String dish) {
        LambdaQueryWrapper<Dish> qDish = new LambdaQueryWrapper<>();

        // 筛选 category name
        if (category != null) {
            LambdaQueryWrapper<Category> qCategory = new LambdaQueryWrapper<>();
            qCategory.eq(Category::getName, category);
            Category c = categoryService.getOne(qCategory);

            if (c != null)
                qDish.eq(Dish::getCategoryId, c.getId());
            else
                return null;
        }

        // 筛选 dish name
        if (dish != null)
            qDish.eq(Dish::getName, dish);

        // 把 category 和 business name 添加到 DishDto 对象上
        List<Dish> dishList = this.list(qDish);
        if (dishList == null || dishList.isEmpty()) {
            return null;
        } else {
            // 返回查询结果
            return dishList.stream().map((item) -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);    // 复制属性

                // 根据 id 查询 category 对象
                Category c = categoryService.getById(item.getCategoryId());
                if (c != null) {
                    dishDto.setCategoryName(c.getName());
                }

                // 根据 id 查询 Business 对象
                Business b = businessService.getById(item.getBusinessId());
                if (b != null) {
                    dishDto.setBusinessName(b.getName());
                }

                return dishDto;
            }).toList();
        }
    }
}
